﻿using System.Text.Json.Serialization;
using Newtonsoft.Json;

namespace Devonline.AspNetCore;

/// <summary>
/// 查询选项
/// </summary>
public class PagedOptions
{
    /// <summary>
    /// 是否返回总数量
    /// </summary>
    [JsonProperty("$count")]
    [JsonPropertyName("$count")]
    public bool? Count { get; set; }
    /// <summary>
    /// 当前页码
    /// </summary>
    [JsonProperty("$top")]
    [JsonPropertyName("$top")]
    public int? Top { get; set; }
    /// <summary>
    /// 页大小
    /// </summary>
    [JsonProperty("$skip")]
    [JsonPropertyName("$skip")]
    public int? Skip { get; set; }

    /// <summary>
    /// odata paged options to paged request
    /// </summary>
    /// <param name="request"></param>
    public static implicit operator PagedOptions(PagedRequest request) => new() { Count = request.Total, Top = request.PageSize, Skip = (request.PageIndex - 1) * request.PageSize };
    /// <summary>
    /// paged request to odata paged options
    /// </summary>
    /// <param name="options"></param>
    public static implicit operator PagedRequest(PagedOptions options)
    {
        var pagedRequest = new PagedRequest
        {
            Total = options.Count,
            PageSize = options.Top.HasValue ? options.Top.Value <= AppSettings.UNIT_ONE ? AppSettings.UNIT_ONE : options.Top.Value : AppSettings.UNIT_ONE
        };

        if (options.Skip.HasValue)
        {
            var skip = options.Skip.Value <= AppSettings.UNIT_ZERO ? AppSettings.UNIT_ZERO : options.Skip.Value;
            pagedRequest.PageIndex = skip == 0 ? 1 : (skip / pagedRequest.PageSize) + 1;
        }
        else
        {
            pagedRequest.PageIndex = AppSettings.UNIT_ONE;
        }

        return pagedRequest;
    }
}